//
//  VehicleListViewController.m
//  阿帕
//
//  Created 阿帕 on 2019/12/25.
//  Copyright © 2019 GCY. All rights reserved.
//

#import "FreightStatisticsViewController.h"

#import "FreightStatisticsCell.h"

@interface FreightStatisticsViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    NSString *_startDate;
    NSString *_endDate;
}
@property (strong , nonatomic)UITextField *textFiled;

@property (strong , nonatomic)UITableView *tableView;

@property (strong , nonatomic)NSMutableArray *dataArray;

@property (strong , nonatomic)UIImageView *foundImageView;

@property (nonatomic, assign) NSInteger pageNum;

@property (strong , nonatomic)UILabel *totalPriceLabel;

@end

@implementation FreightStatisticsViewController

static const CGFloat cellHeight = 60;

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _pageNum = 1;
    _startDate = @"";
    _endDate = @"";
    
    [self baseViewSetup];
    
    [self getCarSourceListRequest];
}

- (void)baseViewSetup {
    
    self.navigationItem.title = @"运费统计";
    
    self.view.backgroundColor = BackgroundColor;
    
    UIButton *resetButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [resetButton setTitle:@"重置" forState:UIControlStateNormal];
    resetButton.titleLabel.font = font(14);
    [resetButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
    [resetButton addTarget:self action:@selector(rightBarItemClick) forControlEvents:UIControlEventTouchUpInside];
        
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:resetButton];
    rightItem.imageInsets = UIEdgeInsetsMake(0, -15,0, 0);//设置向左偏移
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
    UIView *dateBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 40)];
    dateBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: dateBgView];
    
    NSArray *btnTitleArr = @[@"开始时间",@"结束时间"];
    
    for (int i=0; i<btnTitleArr.count; i++) {
        //按钮
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(dateBgView.cy_width/2*i, 0, dateBgView.cy_width/2, dateBgView.cy_height);
        button.tag = 10 + i;
        [button setTitle:btnTitleArr[i] forState:UIControlStateNormal];
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        button.titleLabel.font = font(14);
        [button setImage:image(@"gcy_icon_supply_sTriangle") forState:UIControlStateNormal];
        [button setTitleColor:Dark_TextColor forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnEventClick:) forControlEvents:UIControlEventTouchUpInside];
        [dateBgView addSubview:button];
        
        [button layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];
    }
    
    _textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, dateBgView.cy_bottom + 1, ScreenW, 40)];
    _textFiled.font = font(14);
    _textFiled.text = @"";
    _textFiled.backgroundColor = [UIColor whiteColor];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textFiled.keyboardType = UIKeyboardTypeDefault;
    _textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"司机车牌号/司机手机号/运单号" attributes:@{NSForegroundColorAttributeName: Light_TextColor}];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 20, 40)];
    _textFiled.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 40)];
    _textFiled.leftViewMode = UITextFieldViewModeAlways;
    [_textFiled addSubview: leftView];
    
    
    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenW-40, 10, 20, 20)];
    searchImage.userInteractionEnabled = YES;
    searchImage.image = [UIImage imageNamed:@"gcy_icon_search_siji"];
    _textFiled.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    _textFiled.rightViewMode = UITextFieldViewModeAlways;
    
    [searchImage nyl_addTapGes:^{
        _pageNum = 1;
        [self getCarSourceListRequest];
    }];
    
    [_textFiled addSubview:searchImage];
    
    [self.view addSubview:_textFiled];
    
    [self.view addSubview:self.tableView];
    
    //合计金额
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenH-NavHeight-MenuBarHeight-40, ScreenW, 40)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: bottomView];
    
    _totalPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, ScreenW-30, 40)];
    _totalPriceLabel.text = @"合计：-";
    _totalPriceLabel.textAlignment = NSTextAlignmentRight;
    _totalPriceLabel.font = font(14);
    _totalPriceLabel.textColor = Orange_Color;
    [bottomView addSubview:_totalPriceLabel];
}

- (void)getCarSourceListRequest {
    WEAKSELF
    
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *pamars = @{
        @"searchInfo": _textFiled.text,
        @"pageSize":DEFULT_LOAD_NUM,
        @"pageNum":[NSNumber numberWithInteger:_pageNum],
        @"status": @"5",//已结算
        @"gmtCreatedStart": _startDate,
        @"gmtCreatedEnd": _endDate,
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
    };
    
    __block float totalPrice = 0.00;
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], ORDER_DETAIL) withParameter:pamars withVC:self netName:@"运费统计" success:^(id response, NSString *msg) {
        
        if ([response[@"records"] count] != 0) {
            
            [weakSelf.dataArray addObjectsFromArray:[FreightStatisticsModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            
            [weakSelf.dataArray enumerateObjectsUsingBlock:^(FreightStatisticsModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                totalPrice = obj.deliveryFeePractical + totalPrice;
            }];
            
            _totalPriceLabel.text = CJStringWithFormat(@"合计：%.2f", totalPrice);
            
            weakSelf.tableView.hidden = NO;
            weakSelf.foundImageView.hidden = YES;
            
        } else {
            
            if (_pageNum == 1) {
                weakSelf.foundImageView.hidden = NO;
                weakSelf.tableView.hidden = YES;
                _totalPriceLabel.text = @"合计：0";
            }
            
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            
        }

        [weakSelf.tableView reloadData];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)btnEventClick:(UIButton *)button {
    
    if (button.tag == 10) {
        //开始时间
        BRDatePickerView *datePickerView = [[BRDatePickerView alloc]initWithPickerMode:BRDatePickerModeYMD];
        datePickerView.title = @"选择日期";
        datePickerView.isAutoSelect = NO;
        datePickerView.showToday = NO; // 是否显示“今天”
        datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
            [button setTitle:selectValue forState:UIControlStateNormal];
            [button layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];
            
            _startDate = selectValue;
            _pageNum = 1;
            [self getCarSourceListRequest];
        };
        [datePickerView show:self];
        
    } else if (button.tag == 11) {
        //结束时间
        BRDatePickerView *datePickerView = [[BRDatePickerView alloc]initWithPickerMode:BRDatePickerModeYMD];
        datePickerView.title = @"选择日期";
        datePickerView.isAutoSelect = NO;
        datePickerView.showToday = NO; // 是否显示“今天”
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSDate *date = [formatter dateFromString:_startDate];
        datePickerView.minDate = date;
        datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
            [button setTitle:selectValue forState:UIControlStateNormal];
            [button layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];
            
            _endDate = selectValue;
            _pageNum = 1;
            [self getCarSourceListRequest];
        };
        [datePickerView show:self];
    }
}

- (void)rightBarItemClick {
    
    _startDate = @"";
    _endDate = @"";
    _textFiled.text = @"";
    for (int i=0; i<2; i++) {
        UIButton *button = [self.view viewWithTag:10+i];
        if (i==0) {
            [button setTitle:@"开始时间" forState:UIControlStateNormal];
        } else {
            [button setTitle:@"结束时间" forState:UIControlStateNormal];
        }
        [button layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];
    }
    
    [self getCarSourceListRequest];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FreightStatisticsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = self.dataArray[indexPath.row];
    
    return cell;
}

//上拉刷新数据
- (void)loadNewData{
    _pageNum = 1;
    [self getCarSourceListRequest];
}
- (void)loadMoreData{
    _pageNum ++;
    [self getCarSourceListRequest];
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 40)];
    headerView.backgroundColor = [UIColor whiteColor];

    NSArray *titleArr = @[@"发货人",@"收货人",@"金额",@"结算时间"];
    for (int i=0; i<4; i++) {
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenW/4*i, 0, ScreenW/4, headerView.cy_height)];
        textLabel.text = titleArr[i];
        textLabel.textAlignment = NSTextAlignmentCenter;
        textLabel.textColor = Theme_ColorValue;
        textLabel.font = font(14);
        [headerView addSubview:textLabel];
    }
    
    return headerView;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
}
#pragma mark - LazyLoad
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 82, ScreenW, ScreenH - NavHeight - 82 - 41);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([FreightStatisticsCell class]) bundle:nil] forCellReuseIdentifier:@"CellID"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (UIImageView *)foundImageView {
    if (!_foundImageView) {
        _foundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 170, 170)];
        _foundImageView.image = image(@"gcy_img_list_found");
        _foundImageView.contentMode = UIViewContentModeScaleAspectFit;
        _foundImageView.center = self.view.center;
        [self.view addSubview:_foundImageView];
    }
    return _foundImageView;
}

@end
